<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/25
 * Time: 9:48
 */

namespace app\api\controller\android\v5;


use app\api\model\Authority;

use app\api\model\OrderModel;
use think\Controller;

use think\Request;
use think\Exception;
use app\api\validate;
use  app\api\model\Approval;
use Think\Db;


class MaterialScience extends Controller
{
    protected $model;
    protected $us;
    protected $newTime;
    protected $endTime;
    protected $overtime;
    protected $pdf;
    
    
    public function _initialize()
    {
        $this->model=new Authority();
        
        $this->us=Authority::check(1);
        
    }
    
    
    /**
     * 获取库存列表
     */
    public function Stock_list()
    {
        $data=Request::instance()->post(['type', 'ok']);
        if ($data['type'] == 0) {
            $custom=db('custom_material')
                ->field('id,company,stock_name,latest_cost,number,created_time,number')
                ->where(['store_id'=>$this->us['store_id'], 'status'=>0])
                ->where('number', 'neq', 0)
                ->select();
            foreach ($custom as $k=>$l) {
                $custom[$k]['type']=0;
            }
        } else if ($data['type'] == 99) {
            $cust=db('purchase_usage')
                ->field('id,company,stock_name,latest_cost,number,created_time,content,remake')
                ->where('type', 1)
                ->where('number', 'neq', 0);
            if (isset($data['ok']) && $data['ok'] != '') {
                $cust->where(['status'=>3]);
            }
            $custom=$cust->where('store_id', $this->us['store_id'])
                ->order('created_time desc')
                ->select();
            foreach ($custom as $k=>$l) {
                $custom[$k]['type']=99;
            }
        } else if ($data['type'] == 98) {
            $cooperation_usage=db('cooperation_usage')
                ->join('stock', 'stock.id=cooperation_usage.stock_id', 'left')
                ->field('cooperation_usage.id,cooperation_usage.company,cooperation_usage.stock_name,cooperation_usage.stock_id,cooperation_usage.latest_cost,sum(cooperation_usage.number) as number,cooperation_usage.created_time,cooperation_usage.remake,stock.type')
                ->where('stock.type', $data['type'])
                ->group('cooperation_usage.latest_cost,cooperation_usage.stock_id');
            
            if (isset($data['ok']) && $data['ok'] != '') {
                $cooperation_usage->where(['cooperation_usage.status'=>3]);
            }
            $custom=$cooperation_usage->order('cooperation_usage.created_time desc')
                ->select();
        } else{
            $custom=db('routine_usage')
                ->join('stock', 'stock.id=routine_usage.stock_id', 'left')
                ->field('routine_usage.id,routine_usage.company,routine_usage.stock_name,routine_usage.stock_id,routine_usage.latest_cost,sum(routine_usage.number) as number,routine_usage.created_time,routine_usage.remake,stock.type')
                ->where('routine_usage.store_id', $this->us['store_id'])
                ->where('stock.type', $data['type'])
                ->group('routine_usage.latest_cost,routine_usage.stock_id')
                ->where('routine_usage.status', 3)
                ->select();
            
        }
        
        r_date($custom, 200);
    }
    
    /**
     * 获取库存列表
     */
    public function Stock_list_search()
    {
        $data           =Request::instance()->post(['title']);
        $custom_material=[];
        $purchase_usage =[];
        $routine_usage  =[];
        $custom_material=db('custom_material')
            ->field('id,company,stock_name,latest_cost,number,created_time,number')
            ->where(['store_id'=>$this->us['store_id'], 'status'=>0])
            ->where(['stock_name'=>['like', "%{$data['title']}%"]])
            ->where('number', 'neq', 0)
            ->select();
        foreach ($custom_material as $k=>$l) {
            $custom_material[$k]['type']=0;
        }
        
        $purchase_usage=db('purchase_usage')
            ->field('id,company,stock_name,latest_cost,number,created_time,status,content,remake')
            ->where('type', 1)
            ->where('number', 'neq', 0)
            ->where('status', 3)
            ->where(['stock_name'=>['like', "%{$data['title']}%"]])
            ->where('store_id', $this->us['store_id'])
            ->select();
        foreach ($purchase_usage as $k=>$l) {
            $purchase_usage[$k]['type']=99;
        }
        
        $routine_usage=db('routine_usage')
            ->join('stock', 'stock.id=routine_usage.stock_id', 'left')
            ->field('routine_usage.id,routine_usage.company,routine_usage.stock_name,routine_usage.stock_id,routine_usage.latest_cost,sum(routine_usage.number) as number,routine_usage.created_time,routine_usage.remake,stock.type')
            ->where('routine_usage.store_id', $this->us['store_id'])
            ->where(['routine_usage.stock_name'=>['like', "%{$data['title']}%"]])
            ->group('routine_usage.latest_cost,routine_usage.stock_id')
            ->where('routine_usage.status', 3)
            ->select();
        
        $cooperation_usage=db('cooperation_usage')
            ->join('stock', 'stock.id=cooperation_usage.stock_id', 'left')
            ->field('cooperation_usage.id,cooperation_usage.company,cooperation_usage.stock_name,cooperation_usage.stock_id,cooperation_usage.latest_cost,sum(cooperation_usage.number) as number,cooperation_usage.created_time,cooperation_usage.remake,stock.type')
            ->group('cooperation_usage.latest_cost,cooperation_usage.stock_id')
            ->where(['cooperation_usage.stock_name'=>['like', "%{$data['title']}%"]])
            ->where('cooperation_usage.status', 3)
            ->order('cooperation_usage.created_time desc')
            ->select();
        
        
        r_date(array_merge(array_merge(array_merge($custom_material, $purchase_usage), $routine_usage), $cooperation_usage), 200);
    }
    
    /**
     * 获取库存列表
     */
    public function CollectingStock_list()
    {
        $data=Request::instance()->post(['type', 'ok']);
        if ($data['type'] == 0) {
            $custom=db('custom_material')
                ->field('id,company,stock_name,status,latest_cost,number,created_time,number')
                ->where(['store_id'=>$this->us['store_id'], 'status'=>0])
                ->where('number', 'neq', 0)
                ->select();
            foreach ($custom as $k=>$l) {
                $custom[$k]['type']=0;
            }
        } else if ($data['type'] == 99) {
            $cust=db('purchase_usage')
                ->field('id,company,stock_name,status,latest_cost,number,created_time,content,remake')
                ->where('type', 1)
                ->where('number', 'neq', 0);
            if (isset($data['ok']) && $data['ok'] != '') {
                $cust->where(['status'=>3]);
            }
            $custom=$cust->where('store_id', $this->us['store_id'])
                ->order('created_time desc')
                ->select();
            foreach ($custom as $k=>$l) {
                $custom[$k]['type']=99;
            }
        } else if ($data['type'] == 98) {
            $custom=db('stock')
                ->field('id,company,stock_name,latest_cost,type,class_table')
                ->where('type', 98)
                ->select();
            foreach ($custom as $k=>$value) {
                $custom[$k]['latest_cost']=!empty($value['latest_cost'])? $value['latest_cost'] : 0;
                $custom[$k]['number']     =db('cooperation_usage')
                    ->where('stock_id', $value['id'])
                    ->where('status', 3)
                    ->sum('number');
                $custom[$k]['number']     =db('cooperation_usage')
                    ->where('stock_id', $value['id'])
                    ->where('status', 3)
                    ->value('status');
            }
        } else{
            $custom=db('stock')
                ->field('id,company,stock_name,latest_cost,type,class_table')
                ->where('type', $data['type'])
                ->select();
            
            foreach ($custom as $k=>$value) {
                $custom[$k]['latest_cost']=!empty($value['latest_cost'])? $value['latest_cost'] : 0;
                $custom[$k]['number']     =db('routine_usage')
                    ->where('store_id', $this->us['store_id'])
                    ->where('stock_id', $value['id'])
                    ->where('status', 3)
                    ->sum('number');
                $custom[$k]['state']      =db('routine_usage')
                    ->where('store_id', $this->us['store_id'])
                    ->where('stock_id', $value['id'])
                    ->value('status');
            }
        }
        
        r_date($custom, 200);
    }
    
    /**
     * 获取库存列表
     */
    public function CollectingStock_list_search()
    {
        $data           =Request::instance()->post(['title']);
        $custom_material=[];
        $purchase_usage =[];
        $routine_usage  =[];
        $custom_material=db('custom_material')
            ->field('id,company,stock_name,latest_cost,number,created_time,number')
            ->where(['store_id'=>$this->us['store_id'], 'status'=>0])
            ->where(['stock_name'=>['like', "%{$data['title']}%"]])
            ->where('number', 'neq', 0)
            ->select();
        foreach ($custom_material as $k=>$l) {
            $custom_material[$k]['type']=0;
        }
        
        $purchase_usage=db('purchase_usage')
            ->field('id,company,stock_name,latest_cost,number,created_time,status,content,remake')
            ->where('type', 1)
            ->where('number', 'neq', 0)
            ->where('status', 3)
            ->where(['stock_name'=>['like', "%{$data['title']}%"]])
            ->where('store_id', $this->us['store_id'])
            ->select();
        foreach ($purchase_usage as $k=>$l) {
            $purchase_usage[$k]['type']=99;
        }
        
        $routine_usage=db('stock')
            ->field('id,company,stock_name,latest_cost,type,class_table')
            ->where(['stock_name'=>['like', "%{$data['title']}%"]])
            ->select();
        foreach ($routine_usage as $k=>$value) {
            $routine_usage[$k]['number']=db('routine_usage')
                ->where('store_id', $this->us['store_id'])
                ->where('stock_id', $value['id'])
                ->where('status', 3)
                ->sum('number');
            
        }
        
        
        r_date(array_merge(array_merge($custom_material, $purchase_usage), $routine_usage), 200);
    }
    
    
    /**
     * 获取已选列表
     */
    public
    function get_Material_list()
    {
        $data=Request::instance()->post();
        //材料领用
        $material_usage=db('material_usage')
            ->where(['order_id'=>$data['order_id'], 'types'=>$data['type']])
            ->field('Material_id,material_name,type,square_quantity,total_price,company,unit_price,created_time,id,status,remake')
            ->order('status asc')
            ->select();
        r_date($material_usage, 200);
    }
    
    /**
     * 入库详情列表
     */
    public function get_routine_usage($stock_id)
    {
        $material_usage=db('routine_usage')
            ->where(['stock_id'=>$stock_id])
            ->where('store_id', $this->us['store_id'])
            ->order('id desc')
            ->select();
        $stock         =db('stock')
            ->where(['id'=>$stock_id])
            ->find();
        if ($material_usage) {
            $num=0;
            $pr =0;
            foreach ($material_usage as $k=>$value) {
                if ($value['status'] == 3) {
                    $num+=$value['number'];
                    $pr +=$value['latest_cost'] * $value['number'];
                }
                if ((int)$value['number'] < 0) {
                    unset($material_usage[$k]);
                }
                
            }
            
            $data=['stock_name'=>$stock['stock_name'], 'latest_cost'=>$stock['latest_cost'], 'number'=>$num, 'total_price'=>sprintf('%.2f', $pr), 'data'=>array_merge($material_usage)];
        } else{
            
            $data=['stock_name'=>$stock['stock_name'], 'latest_cost'=>$stock['latest_cost'], 'number'=>0, 'total_price'=>0, 'data'=>$material_usage,];
        }
        r_date($data, 200);
    }
    
    /**
     * 师傅材料审核
     */
    public function get_Material_To_examine()
    {
        $data=Request::instance()->post();
        db()->startTrans();
        try {
            $material_usage=db('material_usage')->where(['id'=>$data['id']])->find();
            $status=$data['status'];
            //材料领用
            db('material_usage')
                ->where(['id'=>$data['id']])
                ->update(['status'=>$status, 'remake'=>$data['remake'], 'adopt'=>time()]);
            
            if ($data['status'] == 2) {
                if ($material_usage['type'] == 0) {
                    $routine_usage=db('custom_material')->where('id', $material_usage['Material_id'])->setInc('number', $material_usage['square_quantity']);
                    
                } elseif ($material_usage['type'] == 99){
                    $routine_usage=db('purchase_usage')->where('id', $material_usage['Material_id'])->setInc('number', $material_usage['square_quantity']);
                } elseif ($material_usage['type'] == 98){
                    $usage_record =db('usage_record')->where(['id'=>$data['id']])->find();
                    $routine_usage=db('cooperation_usage')->where(['id'=>$usage_record['unified']])->update(['status'=>2]);
                } else{
                    $routine_usage=db('usage_record')->where(['id'=>$data['id']])->find();
                    $stock_id     =db('routine_usage')->where(['id'=>$routine_usage['unified']])->find();
                    
                    db('routine_usage')->where(['id'=>$routine_usage['unified']])->update(['status'=>3]);
                    $routine_usage=db('routine_usage')->insertGetId([
                        'stock_name'  =>$material_usage['material_name'],
                        'stock_id'    =>$stock_id['stock_id'],
                        'store_id'    =>$this->us['store_id'],
                        'company'     =>$material_usage['company'],
                        'latest_cost' =>$material_usage['unit_price'],
                        'user_id'     =>$material_usage['user_id'],
                        'number'      =>$material_usage['square_quantity'],
                        'created_time'=>time(),
                    ]);
                    
                }
                if (!$routine_usage) {
                    throw new Exception('更改库存失败');
                }
            } else{
                if ($material_usage['type'] != 0 && $material_usage['type'] != 99) {
                    $routine_usage=db('usage_record')->where(['id'=>$data['id']])->find();
                    db('routine_usage')->where(['id'=>$routine_usage['unified']])->update(['status'=>3]);
                }
            }
            db()->commit();
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
    }
    
    /**
     * 获取费用已选列表
     */
    public
    function get_reimbursement_list()
    {
        $data=Request::instance()->post();
        if (!empty($data['user_id'])) {
            $this->us['user_id']=$data['user_id'];
        }
        //费用报销
        if ($data['type'] == 1) {
            $quer=db('reimbursement');
            if (isset($data['isMaterial'])) {
                $quer->where('classification', 4);
            } else{
                $quer->where('classification', '<>', 4);
            }
            $reimbursement=$quer->where(['order_id'=>$data['order_id'], 'user_id'=>$this->us['user_id'], 'type'=>1])->field('reimbursement_name,money,voucher,created_time,id,status,remake, content as remarks,classification')->select();
        } else{
            $exp =new \think\db\Expression('field(status,0,3,1,2)');
            $quer=db('reimbursement');
            if (isset($data['isMaterial'])) {
                $quer->where('classification', 4);
            } else{
                $quer->where('classification', '<>', 4);
            }
            $reimbursement=$quer->where(['order_id'=>$data['order_id'], 'type'=>2])->field('reimbursement_name,money,voucher,created_time,id,status,remake,user_id, content as remarks,classification')->order($exp)->select();
            foreach ($reimbursement as $k=>$item) {
                $reimbursement[$k]['user_id']=Db::connect(config('database.db2'))->table('app_user')
                    ->where('id', $item['user_id'])
                    ->field('username')
                    ->find()['username'];
            }
        }
        foreach ($reimbursement as $k=>$item) {
            $reimbursement[$k]['voucher']=empty(unserialize($item['voucher']))? [] : unserialize($item['voucher']);
        }
        
        r_date($reimbursement, 200);
    }
    
    /**
     * 师傅报销审核
     */
    public
    function get_Material_To_Reimbursement(Approval $approval)
    {
        $data=Request::instance()->post();
        db()->startTrans();
        try {
            //材料领用
            $reimbursement=db('reimbursement')->where(['id'=>$data['id']])->find();
            
            if ($data['status'] == 1) {
                $my_string                  =unserialize($reimbursement['voucher']);
                $data['name']               =str_replace(' ', '', $reimbursement['reimbursement_name']);
                $data['money']              =$reimbursement['money'];
                $data['type']               =$reimbursement['classification'];
                $data['content']            =$reimbursement['content'];
                $data['work_wechat_user_id']=$this->us['work_wechat_user_id'];
                $data['reserve']            =$this->us['reserve'];
                if (empty($data['work_wechat_user_id'])) {
                    throw new Exception('请联系公司');
                }
                
                $p=$approval->Reimbursement($data, $my_string);
                if ($p['errcode'] != 0) {
                    throw new Exception('企业微信提交失败');
                }
                $p=['status'=>3, 'sp_no'=>$p['sp_no'], 'submission_time'=>time()];
            } else{
                $p=['status'=>2, 'remake'=>$data['remake'], 'submission_time'=>time()];
            }
            db('reimbursement')->where(['id'=>$data['id']])->update($p);
            db()->commit();
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
    }
    
    
    /*
     * 人工结算
     */
    public
    function artificial_list()
    {
        
        $data   =Request::instance()->post();
        $capital=$cap=db('capital')->where(['ordesr_id'=>$data['order_id'], 'types'=>1, 'enable'=>1])->field('class_b,capital_id')->select();
        if (empty($capital)) {
            r_date(null, 300, '数据不存在');
        }
        foreach ($capital as $k=>$kl) {
            $reality_artificial=Db::connect(config('database.db2'))->table('app_user_order_capital')
                ->join('app_user', 'app_user.id=app_user_order_capital.user_id', 'left')
                ->where('app_user_order_capital.capital_id', $kl['capital_id'])
                ->where('app_user_order_capital.deleted_at', 'null')
                ->field('app_user_order_capital.work_time,app_user_order_capital.personal_price,app_user.username,app_user_order_capital.user_id')
                ->select();
//            echo Db::connect(config('database.db2'))->table('app_user_order_capital')->getLastSql();die;
            $capital[$k]['data']=$reality_artificial;;
        }
        r_date($capital, 200);
    }
    
    
    /*
     * 采购添加
     */
    public
    function purchase_usage_material(Approval $approval)
    {
        
        $data=Request::instance()->post();
        db()->startTrans();
        try {
            $validate=new validate\Purchase_usage();
            if (!$validate->check($data)) {
                r_date($validate->getError(), 300);
            }
            if ($data['type'] == 1) {
                $data['work_wechat_user_id']=$this->us['work_wechat_user_id'];
                if (empty($data['work_wechat_user_id'])) {
                    throw new Exception('请联系公司');
                }
                $wechatObj_data=$approval->Purchase($data, json_decode($data['voucher'], true));
                if ($wechatObj_data['errcode'] != 0) {
                    throw new Exception('企业微信提交失败');
                }
                $id=db('purchase_usage')->insertGetId([
                    'stock_name'  =>$data['stock_name'],
                    'company'     =>$data['company'],
                    'latest_cost' =>$data['latest_cost'],
                    'voucher'     =>!empty($data['voucher'])? serialize(json_decode($data['voucher'], true)) : '',
                    'user_id'     =>$this->us['user_id'],
                    'store_id'    =>$this->us['store_id'],
                    'created_time'=>time(),
                    'remake'      =>$data['remake'],
                    'type'        =>1,
                    'number'      =>$data['number'],
                    'status'      =>0,
                    'sp_no'       =>$wechatObj_data['sp_no'],
                ]);
                
            } elseif ($data['type'] == 2){
                $id=db('custom_material')->insertGetId([
                    'stock_name'  =>$data['stock_name'],
                    'company'     =>$data['company'],
                    'latest_cost' =>$data['latest_cost'],
                    'voucher'     =>!empty($data['voucher'])? serialize(json_decode($data['voucher'], true)) : '',
                    'user_id'     =>$this->us['user_id'],
                    'store_id'    =>$this->us['store_id'],
                    'remake'      =>$data['remake'],
                    'created_time'=>time(),
                    'status'      =>0,
                    'number'      =>$data['number'],
                ]);
            }
            
            db()->commit();
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
        
    }
    
    /*
    * 采购收货/入库
    */
    public
    function purchase_usage_Warehousing()
    {
        $data=Request::instance()->post();
        //入库
        $id=db('purchase_usage')->where('id', $data['id'])->update(['status'=>3, 'notes'=>$data['notes'], 'notes_voucher'=>!empty($data['img'])? serialize(json_decode($data['img'], true)) : '']);
        if ($id) {
            r_date($id, 200);
        } else{
            r_date(null, 300);
        }
        
    }
    
    /*
    * 常规材料/入库
    */
    public
    function routine_usage_Warehousing()
    {
        $data=Request::instance()->post();
        //入库
        $id=db('routine_usage')->where('id', $data['id'])->update(['status'=>3, 'notes'=>$data['notes'], 'voucher'=>!empty($data['img'])? serialize(json_decode($data['img'], true)) : '']);
        if ($id) {
            r_date($id, 200);
        } else{
            r_date(null, 300);
        }
        
    }

//    /*
//         * 常规材料直接入库没有收货
//         */
//    public function routine_usage_Warehousing()
//    {
//        $data = Request::instance()->post();
//        //入库
//        $custom = db('stock')
//            ->where('id', $data['id'])
//            ->find();
//
//        if (empty($custom)) {
//            r_date(null, 300, '数据不存在');
//        }
//        $id = db('routine_usage')->insertGetId([
//            'stock_name'   => $custom['stock_name'],
//            'stock_id'     => $custom['id'],
//            'store_id'     => $this->us['store_id'],
//            'company'      => $custom['company'],
//            'latest_cost'  => $custom['latest_cost'],
//            'user_id'      => $this->us['user_id'],
//            'number'       => $data['number'],
//            'status'       => 0,
//            'created_time' => time(),
//        ]);
//        if ($id) {
//            r_date($id, 200);
//        } else {
//            r_date(null, 400);
//        }
//    }
    /*
      * 常规材料直接入库没有收货
      */
    public function routine_Warehousing(Approval $approval)
    {
        $data=Request::instance()->post();
        //入库
        $custom=db('stock')
            ->where(['id'=>$data['id']])
            ->find();
        if (empty($custom)) {
            r_date(null, 300, '数据不存在');
        }
        db()->startTrans();
        try {
            $custom['work_wechat_user_id']=$this->us['work_wechat_user_id'];
            $custom['number']             =$data['number'];
            $custom['remake']             =$data['remake'];
            if (empty($custom['work_wechat_user_id'])) {
                throw new Exception('请联系公司');
            }
            
            $wechatObj_data=$approval->Purchase($custom, '');
            if ($wechatObj_data['errcode'] != 0) {
                throw new Exception('企业微信提交失败');
            }
            $id=db('routine_usage')->insertGetId([
                'stock_name'  =>$custom['stock_name'],
                'stock_id'    =>$custom['id'],
                'store_id'    =>$this->us['store_id'],
                'company'     =>$custom['company'],
                'latest_cost' =>$custom['latest_cost'],
                'user_id'     =>$this->us['user_id'],
                'number'      =>$data['number'],
                'remake'      =>$data['remake'],
                'status'      =>0,
                'created_time'=>time(),
                'sp_no'       =>$wechatObj_data['sp_no'],
            ]);
            
            db()->commit();
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
    }
    
    public
    function list_reimbursement_type($type=1)
    {
        
        
        if ($type == 1) {
            $data=[
                [
                    'name'=>'其它費用',
                    'type'=>1,
                ],
                [
                    'name'=>'材料成本',
                    'type'=>2,
                ],
                [
                    'name'=>'人工成本',
                    'type'=>3,
                ],
            ];
            r_date($data, 200);
        } else{
            $data=[
                [
                    'name'=>'其它費用',
                    'type'=>1,
                ],
                [
                    'name'=>'材料成本',
                    'type'=>2,
                ],
                [
                    'name'=>'人工成本',
                    'type'=>3,
                ],
                [
                    'name'=>'代购主材',
                    'type'=>4,
                ],
            ];
            return $data;
        }
        
    }
    
    public function MaterialList(OrderModel $orderModel, $order_startDate, $order_endDate, $type, $page, $limit=20)
    {
        
        $material_usage=db('material_usage');
        $condition     =[];
        if (!empty($order_startDate) && !empty($order_endDate)) {
            
            $start                    =strtotime($order_startDate . ' 00:00:00');
            $end                      =strtotime($order_endDate . ' 23:59:59');
            $condition['created_time']=['between', [$start, $end]];
        }
        
        if (!empty($type) && $type == 3) {
            $condition['status']=0;
            $condition['types'] =2;
        }
        $article=$material_usage->where('shopowner_id', $this->us['user_id'])->distinct('order_id')->where($condition)->field('order_id')->page($page, $limit)->select();
        $data   =[];
        foreach ($article as $k=>$item) {
            $data[$k]['order_id']=$item['order_id'];
            $data[$k]['address'] =$orderModel->addres($item['order_id']);
            $list                =db('material_usage')->where('order_id', $item['order_id'])->where($condition)->field('material_name,square_quantity,unit_price,user_id,types,total_price,status,types,id')->select();
            foreach ($list as $value) {
                if ($value['types'] == 2) {
                    $value['username']=Db::connect(config('database.db2'))->table('app_user')
                        ->where('id', $value['user_id'])->find()['username'];
                } else{
                    $value['username']=$this->us['username'];
                }
                $data[$k]['data'][]=$value;
                
                
            }
        }
        
        r_date($data, 200);
        
    }
    
    public function ReimbursementList(OrderModel $orderModel, $order_startDate, $order_endDate, $type, $page, $limit=1)
    {
        $isMaterial   =Request::instance()->get();
        $reimbursement=db('reimbursement');
        $condition    =[];
        if (!empty($order_startDate) && !empty($order_endDate)) {
            
            $start                    =strtotime($order_startDate . ' 00:00:00');
            $end                      =strtotime($order_endDate . ' 23:59:59');
            $condition['created_time']=['between', [$start, $end]];
        }
        if (!empty($type) && $type == 4) {
            $condition['status']=0;
            $condition['type']  =2;
        }
        $quer=$reimbursement;
        if (isset($isMaterial['isMaterial'])) {
            
            $quer->where('classification', 4);
        } else{
            
            $quer->where('classification', '<>', 4);
        }
        $list=$quer->where('shopowner_id', $this->us['user_id'])->where($condition)->distinct('order_id')->field('order_id')->order('created_time desc')->page($page, $limit)->select();
        $data=[];
        foreach ($list as $k=>$item) {
            $data[$k]['order_id']=$item['order_id'];
            $data[$k]['address'] =$orderModel->addres($item['order_id']);
            $reimbur             =db('reimbursement');
            
            if (isset($isMaterial['isMaterial'])) {
                $reimbur->where('classification', 4);
            } else{
                $reimbur->where('classification', '<>', 4);
            }
            $lists=$reimbur->where($condition)->where('order_id', $item['order_id'])->field('id,order_id,reimbursement_name,money,user_id,type,status,classification,id')->order('created_time desc')->select();
            foreach ($lists as $value) {
                if ($value['type'] == 2) {
                    $value['username']=Db::connect(config('database.db2'))->table('app_user')
                        ->where('id', $value['user_id'])->find()['username'];
                } else{
                    $value['username']=$this->us['username'];
                }
                if (!empty($value['cleared_time'])) {
                    $value['status']=4;
                }
                $title         =array_search($value['classification'], array_column($this->list_reimbursement_type(2), 'type'));
                $value['title']=$this->list_reimbursement_type(2)[$title]['name'];
                unset($value['classification']);
                $data[$k]['data'][]=$value;
            }
        }
        r_date(array_values($data), 200);
    }
    
    /*
     * 报销详情
     */
    public function ReimbursementInfo($id)
    {
        
        $reimbursement=db('reimbursement')->where('id', $id)->find();
        if ($reimbursement['type'] == 2) {
            $reimbursement['username']=Db::connect(config('database.db2'))->table('app_user')
                ->where('id', $reimbursement['user_id'])->find()['username'];
        } else{
            $reimbursement['username']=$this->us['username'];
        }
        if ($reimbursement['classification'] == 4) {
            $reimbursement['mainMaterialIds']=db('capital')->whereIn('capital_id', $reimbursement['capital_id'])->field('class_b')->select();
        } else{
            $reimbursement['mainMaterialIds']=null;
        }
        $title                        =array_search($reimbursement['classification'], array_column($this->list_reimbursement_type(2), 'type'));
        $reimbursement['title']       =$this->list_reimbursement_type(2)[$title]['name'];
        $reimbursement['created_time']=!empty($reimbursement['created_time'])? date('y-m-d H:i', $reimbursement['created_time']) : '';
        $reimbursement['adopt']       =!empty($reimbursement['adopt'])? date('y-m-d H:i', $reimbursement['adopt']) : '';
        $reimbursement['cleared_time']=!empty($reimbursement['cleared_time'])? date('y-m-d H:i', $reimbursement['cleared_time']) : '';//计算时间
        $reimbursement['voucher']     =!empty($reimbursement['voucher'])? unserialize($reimbursement['voucher']) : null;
        r_date($reimbursement, 200);
        
    }
    
    public function ListSummary()
    {
        
        $data['reimbursementMoney']=sprintf("%.2f", db('reimbursement')->where('shopowner_id', $this->us['user_id'])->where('classification', '<>', 4)->whereNull('cleared_time')->sum('money'));
        $data['materialUsageCount']=db('material_usage')->where('shopowner_id', $this->us['user_id'])->where('status', 0)->count();
        $data['reimbursementCount']=db('reimbursement')->where('shopowner_id', $this->us['user_id'])->where('type', 2)->where('status', 0)->count();
        $data['MaterialCount']     =sprintf("%.2f", db('reimbursement')->where('shopowner_id', $this->us['user_id'])->where('classification', 4)->where('status', 1)->sum('money'));
        
        r_date($data, 200);
    }
    
    
}